﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WebNext.Domain.Entities;
using System.Web.Mvc;
using System.Collections;

namespace WebNext.UI.Models.Comments
{
	public class CommentsViewModel : IEnumerable<CommentViewModel>
	{
		private List<CommentViewModel> comments;

		public CommentViewModel NewComment
		{
			get;
			private set;
		}

		public bool IsLogged
		{
			get;
			private set;
		}
		
		public int Count
		{
			get { return this.comments.Count; }
		}

		public int EntryId
		{
			get;
			private set;
		}

		public CommentsViewModel(IEnumerable<Comment> comments, int entryId, bool isLogged)
		{
			this.EntryId = entryId;
			this.NewComment = new CommentViewModel(0, entryId, null, null);
			this.NewComment.DisplayMode = CommentDisplayMode.Add;
			this.comments = new List<CommentViewModel>(comments.Select(c => new CommentViewModel(c, isLogged)));
		}

		public void Merge(CommentViewModel commentModel)
		{
			if (commentModel.Id == 0)
			{
				this.NewComment.UpdateFrom(commentModel);
			}
			else
			{
				CommentViewModel existingCommentModel = this.comments.FirstOrDefault(t => t.Id == commentModel.Id);
				if (existingCommentModel != null)
				{
					existingCommentModel.UpdateFrom(commentModel);
				}
				else
				{
					this.comments.Add(commentModel);
				}
			}
		}

		public IEnumerator<CommentViewModel> GetEnumerator()
		{
			return this.comments.GetEnumerator();
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return this.comments.GetEnumerator();
		}
	}
}